#include <crtdbg.h>
#include <direct.h>
#include <stdio.h>

#include "toolbox_interchange.hpp"
#include "rdxsupport.hpp"
#include "../../rdx/src/rdx/rdx_ilcomp.hpp"

using namespace RDX;
using namespace RDX::ObjectManagement;
using namespace RDX::Programmability;

int ExportSource_Main()
{
	if(toolResources.argc < 3)
	{
		fprintf(stderr, "Syntax: exportsource [-rdxtextfirst] <output.cpp> <Package list>");
		fprintf(stderr, "        Packages must be detectable via TDPTools.zonepolicy");
		return -1;
	}

	if(!strcmp(toolResources.argv[2], "-rdxtextfirst"))
	{
		toolResources.argv++;
		toolResources.argc--;
	}

	FILE *f = fopen(toolResources.argv[2], "wb");
	if(!f)
	{
		fprintf(stderr, "ERROR: Couldn't open %s for write", toolResources.argv[1]);
		return -1;
	}

	RDX::OperationContext ctx(toolResources.objm);

	for(int i=3;i<toolResources.argc;i++)
	{
		CRef<const String> str1 = toolResources.objm->CreateStringASCII(&ctx, toolResources.argv[i]);
		CRef<const String> str2 = toolResources.objm->CreateStringASCII(&ctx, ".a");
		CRef<const String> symbolStr = toolResources.objm->CreateStringConcatenated(&ctx, str1, str2);

		// Find the domain
		Domain domain = toolResources.pkgHost->DomainForSymbolName(toolResources.objm, symbolStr);
		if(domain == DOMAIN_Invalid)
		{
			fprintf(stderr, "Couldn't resolve domain package for %s", toolResources.argv[i]);
			return -1;
		}

		printf("%s loading ...", toolResources.argv[i]);
		CRef<Package> pkg = toolResources.objm->LoadPackage(&ctx, domain, toolResources.pkgHost);
		if(pkg == NULL)
		{
			fprintf(stderr, "\n\nCouldn't load package for %s", toolResources.argv[i]);
			return -1;
		}

		printf("    exporting ...");
		RDX_ExportSource(toolResources.objm, f, pkg->_native.domain);
		
		printf("Done\n", toolResources.argv[i]);
		toolResources.objm->CollectGarbage(&ctx);
	}

	fclose(f);

	return 0;
}

